<?php


namespace app\mobile\controller;


use think\Request;
use think\Db;

class Wx extends \Common1 {

    public $appid = "wx2434466efe35d732";
    public $secret = "2b2840e23fa64750176a62111a4ba825";

    function getRandomStr($len, $special=true){
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if($special){
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for($i=0; $i<$len; $i++){
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }


    public function getSign(){
        if(isset($_GET["url"])){
            $url = $_GET["url"];
            $output = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->secret");
            $arr = json_decode($output, true);
            if(isset($arr["access_token"])){
                $token = $arr["access_token"];
                $getjsp = file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$token&type=jsapi");
                $brr = json_decode($getjsp, true);
                if(isset($brr["ticket"])){
                    $jsapi_ticket = $brr["ticket"];
                    $noncestr=$this->getRandomStr(10);
                    $timestamp = time();

                    $All_Str = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
                    $sign = sha1($All_Str);
                    $data = [
                        "appId" => $this->appid,
                        "timestamp" => $timestamp,
                        "nonceStr" => $noncestr,
                        "signature" => $sign,
                    ];
                    Code(200, false, $data);
                }else{
                    Code(403, "服务器错误, 请稍后再试");
                }
            }else{
                Code(403, "服务器错误, 请稍后再试");
            }
        }else{
            Code(403, "服务器错误, 请稍后再试");
        }

    }

    public function GetOAuth(){
        $arr_token = getallheaders();
        $login_token = "";
        if(isset($arr_token["Authorization"]) && $arr_token["Authorization"] != ""){
            $login_token = $this->Check($arr_token["Authorization"]);
        }
        if(isset($_GET["code"])){
            $code = $_GET["code"];
            $gettoken = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appid&secret=$this->secret&code=$code&grant_type=authorization_code");
            $arr = json_decode($gettoken, true);
            if(isset($arr["access_token"]) && isset($arr["openid"])){
                $token = $arr["access_token"];
                $openid = $arr["openid"];
                $brr = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=$token&openid=$openid&lang=zh_CN");
                $info = json_decode($brr, true);
                if(isset($info["nickname"]) && isset($info["headimgurl"])){
                    $nickname = $info["nickname"];
                    $avatar = $info["headimgurl"];
                    $user = Db::name("user_buy")->where("openid", $openid)->find();
                    if(is_array($login_token)){
                        $uid = $login_token["id"];
                        $update = [
                            "openid" => $openid,
                            "avatar" => $avatar,
                            "nickname" => $nickname,
                        ];
                        if(!empty($user) && $user["tel1"] != ""){
                            Code(403, "对不起，该微信已经被绑定");
                        }else{
                            Db::name("user_buy")->where("ub_id", $uid)->update($update);
                            Db::name("user_buy")->where("ub_id", $user["ub_id"])->delete();
                            $user_info = Db::name("user_buy")->where("ub_id", $uid)->find();
                            $number = Db::name("num")->where("ub_id", $uid)->select();
                            $nums = [];
                            if(!empty($number)){
                                foreach ($number as $value){
                                    $admin = Db::name("admin")->where("aid", $value["aid"])->find();
                                    $nums[] = [
                                        "sub_id" => (int)$admin["aid"],
                                        "sub_name" => $admin["name"],
                                        "sub_num" => (int)$value["number"]
                                    ];
                                }
                            }
                            $data = [
                                "info" => [
                                    "money" => "",
                                    "phone" => $user_info["tel1"],
                                    "wx" => [
                                        "avatar" => $user_info["avatar"],
                                        "nickname" => $user_info["nickname"]
                                    ],
                                ],
                                "nums" => $nums,
                                "token" => $arr_token["Authorization"]
                            ];
                            Code(200, "绑定微信成功", $data);
                        }
                    }else{
                        if(!empty($user)){
                            if($user["avatar"] != $avatar || $user["nickname"] != $nickname){
                                $up = [
                                    "avatar" => $avatar,
                                    "nickname" => $nickname
                                ];
                                Db::name("user_buy")->where("ub_id", $user["ub_id"])->update($up);
                                $user = Db::name("user_buy")->where("ub_id", $user["ub_id"])->find();
                            }
                            $number = Db::name("num")->where("ub_id", $user["ub_id"])->select();
                            $nums = [];
                            if(!empty($number)){
                                foreach ($number as $value){
                                    $admin = Db::name("admin")->where("aid", $value["aid"])->find();
                                    $nums[] = [
                                        "sub_id" => (int)$admin["aid"],
                                        "sub_name" => $admin["name"],
                                        "sub_num" => (int)$value["number"]
                                    ];
                                }
                            }
                            $new_arr = [
                                "time" => time(),
                                "id" => $user["ub_id"]
                            ];
                            $new_token = $this->MakeToken($new_arr);
                            if($user["tel1"] == ""){
                                $data = [
                                    "info" => [
                                        "money" => "",
                                        "phone" => $user["tel1"],
                                        "wx" => [
                                            "avatar" => $user["avatar"],
                                            "nickname" => $user["nickname"]
                                        ]
                                    ],
                                    "nums" => $nums,
                                    "token" => $new_token
                                ];
                                Code(200, "微信授权成功，初次登陆请绑定手机号", $data);
                            }else{
                                $data = [
                                    "info" => [
                                        "money" => "",
                                        "phone" => $user["tel1"],
                                        "wx" => [
                                            "avatar" => $user["avatar"],
                                            "nickname" => $user["nickname"]
                                        ]
                                    ],
                                    "nums" => $nums,
                                    "token" => $new_token
                                ];
                                Code(200, false, $data);
                            }
                        }else{
                            $add = [
                                "openid" => $openid,
                                "avatar" => $avatar,
                                "nickname" => $nickname,
                            ];
                            $id = Db::name("user_buy")->insertGetId($add);
                            $up = [
                                "name" => "User_".$id
                            ];
                            Db::name("user_buy")->where("ub_id", $id)->update($up);
                            $new_arr = [
                                "time" => time(),
                                "id" => $id
                            ];
                            $new_token = $this->MakeToken($new_arr);
                            $data = [
                                "info" => [
                                    "money" => "",
                                    "phone" => "",
                                    "wx" => [
                                        "avatar" => $avatar,
                                        "nickname" => $nickname
                                    ]
                                ],
                                "nums" => [],
                                "token" => $new_token
                            ];
                            Code(200, "微信授权成功，初次登陆请绑定手机号", $data);
                        }
                    }
                }else{
                    Code(403, "服务器错误, 请稍后再试");
                }
            }else{
                if($arr["errcode"] != 40163){
                    Code(403, "服务器错误, 请稍后再试");
                }else{
                    Code(200, false);
                }
            }
        }else{
            Code(403, "服务器错误, 请稍后再试");
        }
    }

}